<!--
 * @Author: zhangjingyu
 * @Date: 2020-12-02 11:02:50
 * @LastEditors: zhangjingyu
 * @LastEditTime: 2021-01-04 09:33:13
 * @FilePath: \vprisk10.14\src\views\SystemMange\nodeManage.vue
 * @Description: 计算节点管理
-->

<template>
  <!-- 节点管理页面 -->
  <div class="nodeManage container">
    <upper-template
      @search="searchForm.page=1,searchFunc()"
      @clear="(searchForm.nodeCode = ''), (searchForm.nodeIp = '')"
    >
      <div slot="buttonArea">
        <el-button @click="addFunc()">新增</el-button>
        <el-button @click="editFunc()">编辑</el-button>
        <el-button @click="delFunc()">删除</el-button>
        <el-button @click="enable('1')">启用</el-button>
        <el-button @click="enable('2')">停用</el-button>
      </div>
      <div slot="searchArea">
        <el-form
          :model="searchForm"
          ref="searchForm"
          label-width="120px"
          label-position="left"
          size="mini"
        >
          <el-form-item label="计算节点编号：">
            <el-input v-model="searchForm.nodeCode"></el-input>
          </el-form-item>
          <el-form-item label="计算节点IP：" prop="nodeIp">
            <el-input v-model="searchForm.nodeIp"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="columnHide">
        <el-checkbox-group v-model="checkList">
          <el-checkbox
            v-for="item in textData"
            :label="item.label"
            :key="item.prop"
            >{{ item.label }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </upper-template>
    <el-row>
      <el-table
        ref="multipleTable"
        :data="tableData"
        style="width: 100%"
        @row-click="rowCheck"
      >
        <el-table-column
          width="55"
          type="selection"
          
        ></el-table-column>
        <el-table-column prop="nodeCode" label="节点编号" v-if="tablePick[0]" show-overflow-tooltip >
        </el-table-column>
        <el-table-column prop="rootPath" label="节点根路径" v-if="tablePick[1]" show-overflow-tooltip >
        </el-table-column>

        <el-table-column
          prop="nodeIp"
          label="节点IP "
          v-if="tablePick[2]"
          align="right"
          show-overflow-tooltip 
        >
        </el-table-column>

        <el-table-column
          prop="threadNum"
          label="线程数"
          sortable
          v-if="tablePick[4]"
          align="right"
        >
        </el-table-column>
        <el-table-column
          prop="nodePort"
          label="节点端口"
          sortable
          v-if="tablePick[5]"
          align="right"
        >
        </el-table-column>
        <el-table-column
          prop="nodeTypeFlag"
          label="节点类型"
          :formatter="row=>$getLabel(row.nodeTypeFlag,nodeTypeList)"
          sortable
          v-if="tablePick[6]"
        >
        </el-table-column>
        <el-table-column
          prop="serviceType"
          label="服务类型"
          :formatter="row=>$getLabel(row.serviceType,serviceTypeList)"
          sortable
          v-if="tablePick[6]"
        >
        </el-table-column>
        <el-table-column
          prop="nodeStatus"
          label="节点状态 "
          :formatter="row=>$getLabel(row.nodeStatus,nodeStatusList)"
          sortable
          v-if="tablePick[3]"
        >
        </el-table-column>
        <el-table-column
          prop="updateTime"
          label="更新时间"
          show-overflow-tooltip 
          sortable
          v-if="tablePick[7]"
        >
          <template slot-scope="scope">
            <div>
              {{ timeFormat(scope.row.updateTime) }}
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        @size-change="handleSizeChange"
        @refresh="searchFunc"
        @current-change="handleCurrentChange"
        :current-page="searchForm.page"
        :page-size="searchForm.size"
        :total="total"
      ></pagination>
    </el-row>
    <el-dialog
      v-dialogDrag
      :title="saveTitles[saveFlg - 1]"
      :visible.sync="addOrEdit"
      top="2%"
      width="514px"
    >
      <el-form
        :model="saveForm"
        ref="saveForm"
        label-width="100px"
        label-position="left"
        :rules="saveFormRules"
      >
        <el-form-item label="节点编码：" prop="nodeCode">
          <el-input
            v-model="saveForm.nodeCode"
            maxlength="40"
            :disabled="saveFlg == 2"
          ></el-input>
        </el-form-item>
        <el-form-item label="节点根路径：" prop="rootPath">
          <el-input v-model="saveForm.rootPath" maxlength="40"></el-input>
        </el-form-item>
        <el-form-item label="节点IP：" prop="nodeIp">
          <el-input v-model="saveForm.nodeIp" maxlength="40"></el-input>
        </el-form-item>
        <el-form-item label="节点端口：" prop="nodePort">
          <el-input v-model="saveForm.nodePort" maxlength="40"></el-input>
        </el-form-item>
        <el-form-item label="线程数：" prop="threadNum">
          <el-input v-model="saveForm.threadNum" maxlength="40"></el-input>
        </el-form-item>
        <el-form-item label="节点类型：" prop="nodeTypeFlag">
          <el-select
            v-model="saveForm.nodeTypeFlag"
            placeholder="请选择"
            style="100%"
          >
            <el-option
              v-for="item in nodeTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务类型：" prop="serviceType">
          <el-select
            v-model="saveForm.serviceType"
            placeholder="请选择"
            style="100%"
          >
            <el-option
              v-for="item in serviceTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span style="color: red"
        >*节点根路径参考引擎端配置文件application.conf</span
      >
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveFunc">确 定</el-button>
        <el-button @click="addOrEdit = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { systemManage } from "@/api/index";
import moment from "moment";
export default {
  data() {
    return {
      addOrEdit: false, // 新增/编辑/查看弹窗
      saveFlg: 1, // 1:新增，2：编辑，3查看,
      saveTitles: ["添加计算节点信息", "编辑计算节点信息"],
      searchForm: {
        nodeCode: "",
        nodeIp: "",
        page: 1,
        size: 15
      },
      total: 0,
      saveForm: {
        nodeCode: "",
        rootPath: "",
        nodeIp: "",
        nodePort: "",
        threadNum: "",
        nodeTypeFlag: "",
        serviceType: ""
      },
      saveFormRules: {
        nodeCode: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[A-Za-z0-9]{1,40}$/,
            message: "只能输入1-40位字母、数字或下划线",
            trigger: "blur" 
          },
            {validator:this.nodeCodeValid,trigger:"blur"}
        ],
        rootPath: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ],
        nodeIp: [
          // ip地址
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          // { validator: this.validPassword, trigger: "blur" },
          { pattern: /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/, message: "请输人正确IP格式,例：192.168.22.141" }
        ],
        nodePort: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          { pattern: /^[1-9][0-9]{0,4}$/, message: "只能输入1-5位整数,首位不为0" }
        ],
        threadNum: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          { pattern: /^[1-9][0-9]{0,2}$/, message: "请输入1-3位正整数,首位不为0" }
        ],
        nodeTypeFlag: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ],
        serviceType: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ]
      },
      checkList: [
        "节点编码",
        "节点根路径",
        "节点IP",
        "线程数",
        "节点端口",
        "节点类型",
        "服务类型",
        "节点状态",
        "更新时间"
      ],
      // 列隐藏
      textData: [
        { label: "节点编码" },
        { label: "节点根路径" },
        { label: "节点IP" },
        { label: "线程数" },
        { label: "节点端口" },
        { label: "节点类型" },
        { label: "服务类型" },
        { label: "节点状态" },
        { label: "更新时间" }
      ],
      // 获取table的数据
      tableData: [],
      nodeStatusList: [],
      nodeTypeList: [],
      serviceTypeList: []
    };
  },
  created() {
    this.getDictAll();
    this.searchFunc();
  },
  computed: {
    tablePick() {
      return this.$tableDataPick(this.checkList, this.textData);
    }
  },
  mounted() {
    // this.getList();
  },
  watch: {
      addOrEdit() {
      // 窗口打开或关闭清除校验结果
      if (this.$refs.saveForm) {
        this.$refs.saveForm.clearValidate();
      }
    },
  },
  methods: {
    // 获取字典
    getDictAll() {
      // 计算节点状态
      this.$getDict("sys_calculateNode_nodeStatus").then(res => {
        if (res.code == 200) {
          this.nodeStatusList = res.datas;
        }
      });
      // 节点类型
      this.$getDict("sys_calculateNode_nodeType").then(res => {
        if (res.code == 200) {
          this.nodeTypeList = res.datas;
        }
      });
      // 服务类型
      this.$getDict("cal_service_type").then(res => {
        if (res.code == 200) {
          this.serviceTypeList = res.datas;
        }
      });
    },
    // nodecode唯一性校验
    nodeCodeValid(rule,value,callback){
      let data = {
        	"nodeCode": value,
	      "operateType": this.saveFlg+""
      }
      systemManage.nodeManageValide(data).then(res=>{
        if(res.code==200){
          callback()
        }else{
          callback(new Error("编号已存在"))
        }
      })
    },
    searchFunc() {
      systemManage.nodeManageQuery(this.searchForm).then(res => {
        if (res.code == 200) {
          this.tableData = res.datas.rows;
          this.total = res.datas.total;
          console.log(res);
        }
      });
      console.log(this.searchForm);
    },
    addFunc() {
      this.saveFlg = 1;
      for (let k in this.saveForm) {
        this.saveForm[k] = "";
      }
      this.addOrEdit = true;
    },
    editFunc() {
      this.saveFlg = 2;
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行修改");
      }
      let row = selection[0];
      let form = { ...row };
      this.saveForm = form;
      this.addOrEdit = true;
    },
    saveFunc() {
      this.$refs["saveForm"].validate(valid => {
        if (valid) {
          let data = {calculateNodeDTO:{...this.saveForm},operateType:this.saveFlg+''};
          systemManage.nodeManageSave(data).then(res => {
            if(res.code==200){
              this.$message.success("保存成功")
              this.addOrEdit = false
              this.searchFunc()
            }else{
              this.$message.error(res.message||'保存失败')
            }
          });
        }
      });
    },
    delFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("您确定要删除选中节点吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = { ids: selection.map(v => v.nodeCode) };
          systemManage.nodeManageRemove(data).then(res => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    enable(data) {
      let val = data === "1" ? "启用" : "停用";
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要" + val + "的节点数据");
      }
      this.$confirm(`您确定要${val}所选数据吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let ajaxStr = val == "启用"?"nodeManageStart":"nodeManageStop"
          console.log(ajaxStr,"ajaxStr")
          let data = {ids:selection.map(v=>v.nodeCode)}
            systemManage[ajaxStr](data).then(res=>{
              if(res.code==200){
                    this.searchFunc()
                this.$message.success(val + "成功");
              }else{
                this.$message.error(res.message || '失败');
              }
            })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消" + val
          });
        });
    },
    // 点击表格右侧显示为xx授权
    rowCheck(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$refs.multipleTable.toggleRowSelection(row, true);
      this.userName = row.roleName;
    },
    timeFormat(val) {
      return val ? moment(val).format("YYYY-MM-DD HH:mm:ss") : "-";
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.size = val
      this.searchFunc()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.searchForm.page = val
      this.searchFunc()
    }
  }
};
</script>

<style lang="scss" scoped>
.dialogSearchBox {
  header {
    text-align: center;
    span {
      margin: 0 20px;
    }
  }
}
</style>